//
//  ArtistViewController.m
//  Mecca
//
//  Created by Ryan Enguero on 5/22/14.
//  Copyright (c) 2014 TapDash Heuristics. All rights reserved.
//

#import "ArtistViewController.h"

#import "Constant.h"

#import "JsonClass.h"

#import "ParserClass.h"

#import "PostClass.h"

#import "ArtistTableViewCell.h"

#import "Artist.h"

#import "Album.h"

#import "UIManager.h"

#import "RotationTabViewController.h"

#import "Reachability.h"

#import "FTWAPI.h"

#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)

@interface ArtistViewController (){
    
    
    FTWAPI *ftwApi;
    
    NSDictionary* json;
    NSArray *artistArr;
    NSArray *searchResults;
    
}

@end

@implementation ArtistViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
        //self.title = NSLocalizedString(@"Artist", @"Artist");
    }
    return self;
}



- (void)viewDidLoad
{
    [super viewDidLoad];
    
    if (!ftwApi) {
        ftwApi = [FTWAPI sharedInstance];
    }
    
    [self.navigationController.navigationBar setHidden:YES];
    
    [self.tableView setBackgroundColor:[UIColor colorWithRed:28/255.0 green:28/255.0 blue:28/255.0 alpha:1.0]];
    
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"cancelNewsFeed" object:@"cancelNews"];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"cancelTopsDL" object:@"cancelTopsDL"];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(somethingHappens:) name:@"cancelArtistFeeds" object:nil];
    
    self.receivedData = [NSMutableData data];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:artistUrl]];
    _theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
    
    [self setupPullToRefresh];
    
}



-(void)setupPullToRefresh
{
    
    UITableViewController *tableViewController = [[UITableViewController alloc] init];
    tableViewController.tableView = self.tableView;
    
    _refreshControll = [[UIRefreshControl alloc] init];
    _refreshControll.tintColor = [UIColor redColor];
    //    refresh.attributedTitle = [[NSAttributedString alloc] initWithString:@"Pull to Refresh"];
    [_refreshControll addTarget:self action:@selector(refreshTable) forControlEvents:UIControlEventValueChanged];
    tableViewController.refreshControl = _refreshControll;
}

-(void)refreshTable{
    
    [self.tableView reloadData];
}



-(void)viewDidAppear:(BOOL)animated{
    
    self.activityLoader.hidden = NO;
}

-(void) somethingHappens:(NSNotification*) notification
{
    NSLog(@"notification = %@",[notification object]);
    
    [self.theConnection cancel];
}


-(void)userProfile{
    NSLog(@"User Profile");
    [[UIManager sharedItems]openLeft];
}

- (IBAction)userProfileAction:(id)sender{
    NSLog(@"User Profile");
    [[UIManager sharedItems]openLeft];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)fetchedData:(NSData *)responseData {
    
    json = [JsonClass jsonParser:responseData];
    
    [[ParserClass sharedItems] artistDetails:json];
    
    
    [self.tableView reloadData];

    NSLog(@"artist json= %@", json);
    NSLog(@"artist churva= %@", [[ParserClass sharedItems] artistDetails]);
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    //#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //#warning Incomplete method implementation.
    // Return the number of rows in the section.
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        return [searchResults count];
        
    } else {
        return [[[ParserClass sharedItems] artistDetails] count];
    }
    
    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Configure the cell...
    
    if ([_refreshControll isRefreshing]) {
        [_refreshControll endRefreshing];
    }
    
    
    static NSString *cellIdentifier = @"Cell";
    
    
    
    
    ArtistTableViewCell *cell = (ArtistTableViewCell*)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    
    if (cell == nil) {
        
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ArtistTableViewCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }
    
    Artist *artist;
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        artist = [searchResults objectAtIndex:indexPath.row];
    } else {
        artist = [[[ParserClass sharedItems] artistDetails] objectAtIndex:indexPath.row];
    }
    
    
    
    
    _indexPath2 = indexPath;
    
    if( [indexPath row] % 2){
        [cell setBackgroundColor:[UIColor whiteColor]];
    }else{
        [cell setBackgroundColor:[UIColor colorWithRed:213/255.0 green:213/255.0 blue:213/255.0 alpha:1.0]];
    }
    
    
        
    
    
    cell.fullNameLbl.text = [artist fullName];
    //[cell setImageString:[NSString stringWithFormat:@"http://tapdashheuristics.com/projects/musicapp/backend-panel/%@",[artist profilePicture]]];
    cell.lblNumberOfAlbums.text = [NSString stringWithFormat:@"%@",[artist albumCount]];
    
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    //[[[ParserClass sharedItems]albumDetails] count];
    
    
    
   
    @autoreleasepool {
        
        
        [cell.artistImg setAlpha:0];
        
        [UIView animateWithDuration:0.5 animations:^{
            
            NSString *imageUrl = [NSString stringWithFormat:@"http://192.185.93.102/~boomeran/backend-panel/%@", [artist profilePicture]];
            
            [ftwApi setupCoverImage:cell.artistImg withURL:imageUrl];
            [cell.actIndLoadingImg setHidden:YES];
            [cell.artistImg setAlpha:1];
        } completion:^(BOOL finished) {
            
        }];
        
    }
    
    return cell;
    		
    
}


#pragma mark - Table view delegate

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSLog(@"asdasda");
    
    NSIndexPath *indexPaths = nil;
    Artist *artist = nil;
    
    if (self.searchDisplayController.active) {
        indexPaths = [self.searchDisplayController.searchResultsTableView indexPathForSelectedRow];
        artist = [searchResults objectAtIndex:indexPaths.row];
        
        [[ParserClass sharedItems] getArtistID:[artist artistID]];
        
        [[ParserClass sharedItems] getArtistName:[artist fullName]];
        
        [[ParserClass sharedItems] getArtistImg:[artist profilePicture]];
        
        [self presentViewController:[[UIManager sharedItems] artistTabBars] animated:YES completion:nil];

    } else {
        
        indexPaths = [self.tableView indexPathForSelectedRow];
        
        artist = [[[ParserClass sharedItems] artistDetails] objectAtIndex:indexPaths.row];
        
        [[ParserClass sharedItems] getArtistID:[artist artistID]];
        
        [[ParserClass sharedItems] getArtistName:[artist fullName]];
        
        [[ParserClass sharedItems] getArtistImg:[artist profilePicture]];
        
        [self presentViewController:[[UIManager sharedItems] artistTabBars] animated:YES completion:nil];
    }
    
}




- (void)viewDidUnload{

    //self.tableView = nil;
    [super viewDidUnload];
    
    [[ParserClass sharedItems] emptyArtist];
}

#pragma mark - SearchBar Delegate

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{

    NSLog(@"Searching = %@", searchText);
    
    [self filterContentForSearchText:searchText
                               scope:[[searchBar scopeButtonTitles]
                                      objectAtIndex:[searchBar
                                                     selectedScopeButtonIndex]]];

    NSLog(@"Searching = %@", searchText);
    
}

- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar{

    [searchBar resignFirstResponder];

    return YES;
}

- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
    
    NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"fullName contains[c] %@", searchText];
    searchResults = [[[ParserClass sharedItems] artistDetails] filteredArrayUsingPredicate:resultPredicate];
    
}

-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
    [self filterContentForSearchText:searchString
                               scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
                                      objectAtIndex:[self.searchDisplayController.searchBar
                                                     selectedScopeButtonIndex]]];
    NSLog(@"Searching = %@", searchString);
    
    return YES;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 78;
}


- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    [_receivedData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"Error data = %@", error);
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    
    
    if (connection == self.theConnection) {
        
        [_receivedData appendData:data];
        
        //  NSLog(@"data parse = %@", _receivedData);
        
    }
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    
    if (connection == self.theConnection) {

        if (!(_receivedData == nil)) {
            
            NSLog(@"Count Confirmed");
            
            json = [JsonClass jsonParser:_receivedData];
            
            [[ParserClass sharedItems] artistDetails:json];
            
            [self.tableView reloadData];
            
            NSLog(@"artist json= %@", json);
            
            NSLog(@"artist churva= %@", [[ParserClass sharedItems] artistDetails]);
        }
        
        
        NSLog(@"Finish");
    }
    
}


- (UINavigationController *)navigationController {
    
    
    return nil;
}

- (void)searchDisplayController:(UISearchDisplayController *)controller didLoadSearchResultsTableView:(UITableView *)tableView {
    
    tableView.backgroundColor = [UIColor blackColor];
    
    [tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    
}


@end
